﻿using LogLib;
using MetroFramework;
using MetroFramework.Forms;
using NewCapturerDemo.Config;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NewCapturerDemo
{
    public partial class FormDSLRConfig : MetroForm
    {
        private bool _bInitCompleted = false;

        private CameraOption _option = new CameraOption();

        private Rectangle _rectangle = new Rectangle();

        private Stopwatch sw = new Stopwatch();

        /// <summary>
        /// 连续点击激活次数统计
        /// </summary>
        private int active_click_count = 0;

        private List<KeyValuePair<string, string>> listDevices = new List<KeyValuePair<string, string>>();

        public FormDSLRConfig()
        {     
            LoadConfig();
            InitializeComponent();
        }

        private void LoadConfig()
        {
            if (!File.Exists(_option.ConfigFilePath))
            {
                _option.Save();
            }
            _option.Load();           
        }

        private void InitCamComboBox()
        {
            //listDevices = new Camera().GetAllDevices();
            //if (listDevices.Count == 0)
            //{
            //    AutoMetroMessageBox.Show(this,
            //            "计算机未连接到任何图像设备.",
            //           "错误提示",
            //           MessageBoxButtons.OK,
            //           MessageBoxIcon.Error,
            //           250,
            //           5);
            //    return;
            //}
            //metroComboBoxCamIndex.Items.Clear();
            //for (int i = 0; i < listDevices.Count; i++)
            //{
            //    metroComboBoxCamIndex.Items.Add(i.ToString());
            //}
            //int index = 0;
            //if (!string.IsNullOrEmpty(_option.MonikerString))
            //{
            //    for (int i = 0; i < listDevices.Count; i++)
            //    {
            //        if (listDevices[i].Value.Equals(_option.MonikerString))
            //        {
            //            index = i;
            //        }
            //    }
            //}
            //metroComboBoxCamIndex.SelectedIndex = index;
            //textBoxCamName.Text = listDevices[index].Key;
            //textBoxMoniker.Text = listDevices[index].Value;
        }

        private void InitCtrls()
        {
            //InitCamComboBox();  
            InitResolutionCombox();
            Rectangle rec = _option.ValidRect;
            textBoxVR_X.Text = rec.X.ToString();
            textBoxVR_Y.Text = rec.Y.ToString();
            textBoxVR_Width.Text = rec.Width.ToString();
            textBoxVR_Height.Text = rec.Height.ToString();
            numericUpDownPlayerWidth.Value = _option.VideoPlayerSize.Width;
            numericUpDownPlayerHeight.Value = _option.VideoPlayerSize.Height;
         
            metroTabControl1.SelectedIndex = 0;
        }

        private void InitResolutionCombox()
        {
            char[] symbols = new char[2] { ' ', '×' };
            Size s = _option.FrameSize;
            string strWidth = s.Width.ToString();
            string strHeight = s.Height.ToString();
            metroComboBoxCamResolution.SelectedIndex = 0;
            for (int i = 0; i < metroComboBoxCamResolution.Items.Count; i++)
            {
                string strTemp = metroComboBoxCamResolution.Items[i].ToString();
                string[] strArray = strTemp.Split(symbols, StringSplitOptions.RemoveEmptyEntries);
                if (strWidth == strArray[0] && strHeight == strArray[1])
                {
                    metroComboBoxCamResolution.SelectedIndex = i;
                    break;
                }
            }
        }

        private Size GetSelectedResolution()
        {
            char[] symbols = new char[2] { ' ', '×' };
            string strTemp = metroComboBoxCamResolution.SelectedItem.ToString();
            string[] strArray = strTemp.Split(symbols, StringSplitOptions.RemoveEmptyEntries);
            int w = int.Parse(strArray[0]);
            int h = int.Parse(strArray[1]);
            return new Size(w, h);
        }

        public bool UpdateData()
        {
            if (!CheckInputValidity())
            {
                string strMsg = string.Format("原图有效区域({0})设置有误.", _rectangle.ToString());
                AutoMetroMessageBox.Show(this, strMsg, "输入有误", MessageBoxButtons.OK, MessageBoxIcon.Error, 320, 10);
                return false;
            }

            if (metroComboBoxCamIndex.SelectedIndex == -1)
            {
                _option.CamName = "";
                _option.Index = 0;
                _option.MonikerString = "";
            }
            else
            {
                _option.FrameSize = GetSelectedResolution();
                _option.Index = metroComboBoxCamIndex.SelectedIndex;
                _option.CamName = listDevices[_option.Index].Key;
                _option.MonikerString = listDevices[_option.Index].Value;
            }
            int w = (int)numericUpDownPlayerWidth.Value;
            int h = (int)numericUpDownPlayerHeight.Value;
            _option.VideoPlayerSize = new Size(w, h);
            _option.ValidRect = _rectangle;
            _option.Save();
            return true;
        }

        private bool CheckInput()
        {
            try
            {
                _rectangle.X = int.Parse(textBoxVR_X.Text);
                _rectangle.Y = int.Parse(textBoxVR_Y.Text);
                _rectangle.Width = int.Parse(textBoxVR_Width.Text);
                _rectangle.Height = int.Parse(textBoxVR_Height.Text);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private bool CheckInputValidity()
        {
            if (!CheckInput())
            {
                return false;
            }

            Size s = GetSelectedResolution();
            if (_rectangle.X + _rectangle.Width > s.Width
                || _rectangle.X + _rectangle.Width <= 0)
            {
                return false;
            }

            if (_rectangle.Y + _rectangle.Height > s.Height
                || _rectangle.Y + _rectangle.Height <= 0)
            {
                return false;
            }
            return true;
        }

        private void TabPageCameraSetting_Load(object sender, EventArgs e)
        {
            Invalidate();
        }

        private void metroComboBoxCamResolution_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!_bInitCompleted)
            {
                return;
            }
            Size s = GetSelectedResolution();
            int height = s.Height;
            int width = height / 6 * 5;
            int left = (s.Width - width) / 2;
            textBoxVR_X.Text = left.ToString();
            textBoxVR_Y.Text = "0";
            textBoxVR_Width.Text = width.ToString();
            textBoxVR_Height.Text = s.Height.ToString();
        }

        private void SetRotateFlipType()
        {
            FormRotateFlipSetting form = new FormRotateFlipSetting(_option.RotateFlipValue);
            if (form.ShowDialog() == DialogResult.OK)
            {
                _option.RotateFlipValue = form.Option;
                _option.Save();
                Log.WriteAsync("重新设置镜头旋转和翻转方式为: " + _option.ToString());
            }
        }

        private void panelForbiddenZone_Click(object sender, EventArgs e)
        {
            OnEnterManagerSection();
        }

        /// <summary>
        /// 当进入管理员区域选项时
        /// </summary>
        private void OnEnterManagerSection()
        {
            // 工作页面不允许呼出菜单          
            if (!sw.IsRunning)
            {
                sw.Restart();
                return;
            }
            if (sw.ElapsedMilliseconds > 3000)
            {
                sw.Reset();
                active_click_count = 0;
            }
            else
            {
                active_click_count++;
            }
            if (active_click_count == 3)
            {
                sw.Reset();
                active_click_count = 0;
                Log.WriteAsync("用户打开超级管理员选项");
                SetRotateFlipType();
            }
        }

        private void metroComboBoxCamIndex_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_bInitCompleted)
            {
                int index = metroComboBoxCamIndex.SelectedIndex;
                textBoxCamName.Text = listDevices[index].Key;
                textBoxMoniker.Text = listDevices[index].Value;
            }
        }

        private void FormConfig_Load(object sender, EventArgs e)
        {
            InitCtrls();
            _bInitCompleted = true;
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (UpdateData())
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
        }

        private void buttonCancell_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void panelForbiddenZone_Click_1(object sender, EventArgs e)
        {
            OnEnterManagerSection();
        }
    }
}
